package com.woniuxy.microseckillserver.controller;

import com.alibaba.fastjson.JSONObject;
import com.woniuxy.microcommonserver.bean.seckill_lk.SeckillGoodsInfo;
import com.woniuxy.microcommonserver.bean.seckill_lk.SellRequest;
import com.woniuxy.microcommonserver.res.ResultMsg;
import com.woniuxy.microseckillserver.service.ISeckillService;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;

/**
 * @Author: 刘康
 * @Date: 2021/1/22 14:59
 * @Description:
 */
@RestController
@RequestMapping("/seckill")
public class SeckillController {

    @Resource
    private ISeckillService seckillServiceImpl;
    @Resource
    private ValueOperations valueOperations;
    @Resource
    private RabbitTemplate rabbitTemplate;

    @PostMapping(value = "/more",produces = MediaType.APPLICATION_JSON_VALUE)
    public ResultMsg saveSeckillGoods(@RequestBody SeckillGoodsInfo seckillGoodsInfo){

        seckillServiceImpl.saveSeckillGoods(seckillGoodsInfo);

        return ResultMsg.builder().code(200).msg("新增成功").build();
    }

    @PutMapping(value = "/updateSeckillGoods",produces = MediaType.APPLICATION_JSON_VALUE)
    public ResultMsg updateSeckillGoods(@RequestBody SeckillGoodsInfo seckillGoodsInfo){

        seckillServiceImpl.updateSeckillGoods(seckillGoodsInfo);

        return ResultMsg.builder().code(200).msg("修改成功").build();
    }

    @DeleteMapping(value = "/updateSeckillGoods",produces = MediaType.APPLICATION_JSON_VALUE)
    public ResultMsg deleteSeckillGoods(@RequestBody Long id){

        seckillServiceImpl.deleteSeckillGoods(id);

        return ResultMsg.builder().code(200).msg("删除成功").build();
    }

    @RequestMapping(value = "/sellSeckillGoods",produces = MediaType.APPLICATION_JSON_VALUE)
    public ResultMsg sellSeckilGoods(@RequestBody SellRequest sellRequest){

        if (valueOperations.setIfAbsent("check_"+sellRequest.getGoodsID()+"_"+sellRequest.getUserId(),"check_True")){
            //第一次购买
            rabbitTemplate.convertAndSend("order.exchange","order.info", JSONObject.toJSONString(sellRequest));

            return ResultMsg.builder().code(200).msg("订单已提交").build();
        }else {
            return ResultMsg.builder().code(200).msg("请勿重复购买").build();
        }

    }


}
